package com.leexuan.ordersystem.actions;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.leexuan.ordersystem.beans.Customer;
import com.leexuan.ordersystem.beans.Order;
import com.leexuan.ordersystem.db.CustomerDB;
import com.leexuan.ordersystem.db.InvoiceDB;
import com.leexuan.ordersystem.db.OrderDB;

public class AddInvoiceAction extends Action {

	public AddInvoiceAction() {
		super();
	}

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {

		int oid = Integer.parseInt(request.getParameter("oid"));

		OrderDB odb = new OrderDB();
		CustomerDB cdb = new CustomerDB();
		InvoiceDB idb = new InvoiceDB();

		try {
			idb.getConnection();

			HttpSession session = request.getSession();

			if (idb.hasInvoice(oid)) {

				session.setAttribute("hasInvoice", "yes");
			} else {

				session.setAttribute("hasInvoice", "no");
			}

			odb.getConnection();

			Order order = odb.getOrder(oid);

			cdb.getConnection();

			Customer cs = cdb.getCustomer(order.getCid());

			session.setAttribute("order", order);
			session.setAttribute("customer", cs);

			return mapping.findForward("success");

		} catch (Exception e) {

			return (new ActionForward(mapping.getInput()));
		} finally {
			try {
				odb.closeConnection();
				cdb.closeConnection();
				idb.closeConnection();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

}
